# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.views.generic.simple import direct_to_template
from lr.table.forms import NewWorkForm
from lr.work.models import Work, WorkRels, Page, WorkComments, Comment, Visitor,\
    Visit
from lr.message.models import LrMessage
from django.template.loader import render_to_string
from lr.register.models import Profile, Invite
from lr.face.views import check_user
from django.shortcuts import render_to_response
from lr.cabinet.models import UserRels
from lr.bank.models import Transaction, BankException, Bank
from django.db.models import Q
from django.db.models.aggregates import Sum
from lr.bookcase.models import Bookcase
from lr import settings


def table(request):
    """ Обработчик запросов к столу """
    if 'filter' in request.GET:
        if request.profile.is_writer():
            filtr = request.GET['filter']
            if filtr == 'works':
                return table_fworks(request)
            elif filtr == 'reviews':
                return table_freviews(request)
        else:
            return HttpResponseRedirect('/')
    elif 'select' in request.GET:
        if request.user.is_authenticated():
            select = request.GET['select']
            if select == 'works':
                return table_works(request)
            elif select == 'new' \
            and request.profile.is_writer():
                return table_new(request)
        return HttpResponseRedirect('/')            
    elif 'edit' in request.GET:
        if request.user.is_authenticated():
            work_id = request.GET['edit']
            return table_edit(request, work_id, request.GET.get('page', 1))
        else:
            return HttpResponseRedirect('/')            
    elif 'view' in request.GET:
        if not check_user(request):
            return render_to_response('lock_account.html')
        work_id = request.GET['view']
        return table_view(request, work_id, request.GET.get('page', 1))
    elif not request.profile.is_writer():
        if not request.user.is_authenticated() \
        or len(Work.objects.filter(owner=request.user).only('id')) == 0:
            # Юзер не автор, не авторизован и не имеет в своем распоряжении работ
            return HttpResponseRedirect('/')
    
    return table_main(request)


def comment(request):
    """ Препроцессор для запроса и размещения нового комментария к работе """
    if request.method == 'POST' and 'work' in request.POST:
        work_id = request.POST['work']
        comment_id = 0
        if 'comment' in request.POST:
            # Запрос на комментарий
            comment_id = request.POST['comment']
        elif 'root' in request.POST:
            # Новый комментарий
            comment_id = request.POST['root']
        
        request.session['comment_post'] = request.POST
        if comment_id:
            return HttpResponseRedirect('table?view=%s#a%s' % (work_id, comment_id))
        else:
            return HttpResponseRedirect('table?view=%s' % work_id)
    
    return HttpResponseRedirect('/')


def table_main(request):
    """ Заглавная страница рабочего стола """
    table_data = {}
    table_data['is_writer'] = request.profile.is_writer()
    return direct_to_template(request, 'table/table.html', table_data)


def table_fworks(request):
    """ Список произведений """
    works = Work.objects.filter(Q(author=request.user) | Q(owner=request.user), fosterling=None)
    work_list = []
    for work in works:
        work_list.append(work)
    if request.user.is_authenticated():
        trustee = WorkRels.objects.filter(coauthors__id=request.user.id, work__fosterling=None)
        for trust in trustee:
            work_list.append(trust.work)
    table_data = {}
    table_data['is_writer'] = request.profile.is_writer()
    table_data['works'] = _create_works_data(request, work_list)
    table_data['filter'] = "work"
    return direct_to_template(request, 'table/table_works.html', table_data)


def table_freviews(request):
    """ Список рецензий """
    works = Work.objects.filter(Q(author=request.user) | Q(owner=request.user)).exclude(fosterling=None)
    work_list = []
    for work in works:
        work_list.append(work)
    if request.user.is_authenticated():
        trustee = WorkRels.objects.filter(coauthors__id=request.user.id).exclude(work__fosterling=None)
        for trust in trustee:
            work_list.append(trust.work)
    table_data = {}
    table_data['is_writer'] = request.profile.is_writer()
    table_data['works'] = _create_works_data(request, work_list)
    table_data['filter'] = "review"
    return direct_to_template(request, 'table/table_works.html', table_data)


def table_works(request):
    """ Список работ """
    works = Work.objects.filter(Q(author=request.user) | Q(owner=request.user))
    work_list = []
    for work in works:
        work_list.append(work)
    if request.user.is_authenticated():
        trustee = WorkRels.objects.filter(coauthors__id=request.user.id)
        for trust in trustee:
            work_list.append(trust.work)
    table_data = {}
    table_data['is_writer'] = request.profile.is_writer()
    table_data['works'] = _create_works_data(request, work_list)
    table_data['filter'] = "none"
    return direct_to_template(request, 'table/table_works.html', table_data)


def _create_works_data(request, works):
    """ Вспомогательная функция, формирующая данные для списка работ """
    works_data = []
    for work in works:
        work_data = {}
        work_data['id'] = work.id
        work_data['title'] = work.title
        can_edit = work.status == u'draft'
        master = work.owner or work.author
        if can_edit and request.user != master:
            if len(WorkRels.objects.filter(work=work, coauthors__id=request.user.id)) == 0:
                can_edit = False
        work_data['can_edit'] = can_edit
        works_data.append(work_data)
    return works_data


def table_new(request):
    """ Создать новую работу """
    table_data = {}
    
    if 'fosterling' in request.session:
        fosterling = request.session['fosterling']
        del request.session['fosterling']
    else:
        fosterling = None
    
    if request.method == 'POST':
        form = NewWorkForm(request.POST)
        if form.is_valid():
            # Создать новое произведение
            try:
                fosterling = Work.objects.get(id=request.POST['fosterling'])
            except:
                fosterling = None
            work_id = _create_work(request.user, request.POST, fosterling)
            return HttpResponseRedirect('table?edit=' + str(work_id))
        table_data['text'] = request.POST['text']
    else:
        form = NewWorkForm()
        table_data['text'] = ''
    
    table_data['form'] = form
    table_data['fosterling'] = fosterling
    return direct_to_template(request, 'table/table_new.html', table_data)


def _create_work(user, data, fosterling=None):
    work = Work.objects.createWork(author=user, title=data['title'], page_title=data['page_title'],
                                   genre=data['genre'], text=data['text'], fosterling=fosterling)
    return work.id


def table_edit(request, work_id, page_index=1):
    """ Редактировать произведение """
    try:
        work = Work.objects.get(id=work_id)
    except:
        name, gender = Profile.get_user_name(user=request.user, profile=request.profile)
        LrMessage.objects.create_message(user=request.user, title=u'Произведение не найдено',
                                         description=render_to_string('messages/work_is_not_exists.html',
                                                                      { 'gender': gender, 'name': name }))
        return HttpResponseRedirect('message')
    
    if work.status != 'draft':
        # Произведение опубликовано и не может быть отредактировано
        if work.owner and request.user == work.owner \
        or not work.owner and request.user == work.author:
            name, gender = Profile.get_user_name(user=request.user, profile=request.profile)
            LrMessage.objects.create_message(user=request.user, title=u'Произведение опубликовано',
                                             description=render_to_string('messages/work_is_published.html',
                                                                          { 'gender': gender, 'name': name, 'work_title': work.title }))
            return HttpResponseRedirect('message')
        else:
            return HttpResponseRedirect('table?view=%s' % str(work_id))
    
    if work.owner and request.user == work.owner \
    or not work.owner and request.user == work.author:
        is_owner = True
        can_edit = True
    elif len(WorkRels.objects.filter(work=work, coauthors__id=request.user.id)) > 0:
        is_owner = False
        can_edit = True
    else:
        is_owner = False
        can_edit = False
    
    if not can_edit or not UserRels.check_rels(work.owner or work.author, request.user):
        # Этот пользователь не имеет права редактировать работу
        return HttpResponseRedirect('table?view=%s' % str(work_id))
    
    pages = Page.objects.filter(work=work, edition=work.edition).order_by('index')
    sel_pages = pages.filter(index=page_index)
    if len(sel_pages) == 0:
        # Указанная страница не существует, взять первую
        page = pages[0]
    else:
        page = sel_pages[0]
    
    if request.method == 'POST' \
    and 'page_title' in request.POST \
    and 'page_text' in request.POST:
        # Сохранить изменения
        page.title = request.POST['page_title']
        page.text = request.POST['page_text']
        page.save()
    
    table_data = {}
    table_data['work_id'] = work_id
    table_data['work_title'] = work.title
    table_data['page_title'] = page.title
    table_data['page_text'] = page.text
    table_data['page_list'] = pages
    table_data['page_index'] = int(page_index)
    table_data['is_owner'] = is_owner
    table_data['fosterling'] = work.fosterling
    return direct_to_template(request, 'work/work_edit.html', table_data)


def table_view(request, work_id, page_no=1):
    """ Смотреть произведение """
    try:
        work = Work.objects.get(id=work_id)
    except:
        name, gender = Profile.get_user_name(user=request.user, profile=request.profile)
        LrMessage.objects.create_message(user=request.user, title=u'Произведение не найдено',
                                         description=render_to_string('messages/work_is_not_exists.html',
                                                                      { 'gender': gender, 'name': name }))
        return HttpResponseRedirect('message')
    
    if request.user.is_authenticated() and request.user.is_active:
        # Авторизованный пользователь        
        if work.owner:
            has_owner = True
            is_owner = request.user == work.owner
        else:
            has_owner = False
            is_owner = False
        is_author = request.user == work.author
        is_coauthor = len(WorkRels.objects.filter(work=work, coauthors__id=request.user.id)) > 0
        is_trustee = len(WorkRels.objects.filter(work=work, trustee__id=request.user.id)) > 0
        is_viewer = len(WorkRels.objects.filter(work=work, viewers__id=request.user.id)) > 0
        is_writer = request.profile.is_writer()
        is_authorized = True
        can_comment = True
        cash = Bank.objects.get(user=request.user).cash
    else:
        # Неавторизованный пользователь
        has_owner = work.owner != None
        is_owner = False
        is_author = False
        is_coauthor = False
        is_trustee = False
        is_viewer = False
        is_writer = False
        is_authorized = False
        can_comment = False
        cash = 0
     
    table_data = {}
    table_data['work_title'] = work.title
    table_data['work_id'] = work.id
    table_data['is_authorized'] = is_authorized
    table_data['is_writer'] = is_writer
    
    if cash >= 10:
        table_data['cash'] = 10
    else:
        table_data['cash'] = cash
    
    is_master = has_owner and is_owner or not has_owner and is_author
    table_data['is_master'] = is_master
    
    can_view = True
    for_contest = work.contest != None
    
    if work.status == 'draft':
        # Произведение не опубликовано
        is_published = False
        
        if not UserRels.check_rels(work.owner or work.author, request.user) \
        or not is_trustee and not is_coauthor and not is_master:
            # Этот пользователь не имеет права смотреть
            # неопубликованное произведение
            can_view = False
            table_data['message'] = render_to_string('messages/work_is_unavailable.html')
            table_data['locked'] = True
    else:
        is_published = True
        table_data['date'] = work.date
        table_data['author_id'] = work.author.id
        table_data['signature'] = work.signature
        
        if for_contest:
            # Это конкурсное произведение
            can_view = False
            if request.user.is_authenticated():
                if work.contest.initiator == request.user or is_author or is_coauthor or is_trustee:
                    # Этот пользователь - заказчик или автор или один из доверенных и может смотреть произведение
                    can_view = True
            if not can_view:
                LrMessage.objects.create_message(user=request.user, title=u'Просмотр закрыт',
                                     description=render_to_string('messages/work_closed.html',
                                                                  { 'contest': work.contest, 'work': work }))
                return HttpResponseRedirect('message')
        else:
            # Это обычное произведение
            if work.status == 'closed':
                # Закрытый доступ
                if not is_trustee and not is_coauthor and not is_viewer and not is_master:
                    # Этот пользователь не имеет права смотреть
                    # закрытое произведение
                    can_view = False
                    if request.method == 'POST' \
                    and 'pay' in request.POST:
                        # Пользователь пытается заплатить за просмотр произведения
                        can_view = _pay_for_view(request, work)
                        if not can_view:
                            _make_has_no_money_message(request.user, request.profile)
                            return HttpResponseRedirect('message')
                    if not can_view:
                        table_data['view_price'] = '%.2f' % work.view_price
                        table_data['annotation'] = work.annotation
                        table_data['message'] = render_to_string('messages/work_is_closed.html')
    
    if can_view:
        # Этот пользователь имеет право просматривать произведение
        if is_authorized:
            like_it = len(WorkRels.objects.filter(work=work, likers__id=request.user.id)) > 0
            dislike_it = len(WorkRels.objects.filter(work=work, dislikers__id=request.user.id)) > 0
        else:
            like_it = False
            dislike_it = False
            
        target_comment = 0
        
        # Составить списки забаненных и игнорируемых пользователей
        # Пользователи, которым запрещено комментировать конкретно это произведение
        work_ban_list = {}
        banned = WorkRels.objects.get(work=work).banned.all()
        for ban in banned:
            work_ban_list[ban.username] = ban.id
        # Пользователи, которым запрещено комментировать все произведения этого владельца
        ban_list = {}
        banned = UserRels.objects.get(user=work.owner or work.author).banned.all()
        for ban in banned:
            ban_list[ban.username] = ban.id
        # Пользователи, которых игнорирует читатель
        ignor_list = {}
        if is_authorized:
            ignored = UserRels.objects.get(user=request.user).ignored.all()
            for ignor in ignored:
                ignor_list[ignor.username] = ignor.id
        # Пользователи, которых игнорирует владелец произведения
        master_ignor_list = {}
        ignored = UserRels.objects.get(user=work.owner or work.author).ignored.all()
        for ignor in ignored:
            master_ignor_list[ignor.username] = ignor.id
        
        if request.user.is_authenticated():
            im_banned = request.user.username in ban_list or request.user.username in work_ban_list
            im_ignored = request.user.username in master_ignor_list
        else:
            im_banned = False
            im_ignored = False
        
        can_review = not work.fosterling and is_writer and not is_author and not im_banned and not im_ignored
        
        # Определить, находится ли произведение в избранном или рекомендованном
        is_favorite = Bookcase.objects.filter(favorites__id=work.id).count() > 0
        is_recommend = Bookcase.objects.filter(recommended__id=work.id).count() > 0
        
        if request.method == 'POST':
            # Действие пользователя
            donate = 0
            if 'donate1' in request.POST:
                donate = 1
            elif 'donate5' in request.POST:
                donate = 5
            elif 'donate10' in request.POST:
                donate = 10
            elif 'like' in request.POST:
                if not like_it and not dislike_it and not is_master:
                    _vote_work(True, request.user, work)
                    like_it = True
            elif 'dislike' in request.POST:
                if not like_it and not dislike_it and not is_master:
                    _vote_work(False, request.user, work)
                    dislike_it = True
            elif 'buy' in request.POST:
                if not is_master:
                    if _buy_work(request, work):
                        name, gender = Profile.get_user_name(user=request.user, profile=request.profile)
                        LrMessage.objects.create_message(user=request.user, title=u'Сделка завершена',
                                             description=render_to_string('messages/buy_work_complete.html',
                                                                          { 'gender': gender, 'name': name,
                                                                            'title': work.title,
                                                                            'link': 'work?id=%d;action=publish' % work.id }))
                    else:
                        _make_has_no_money_message(request.user, request.profile)
                    return HttpResponseRedirect('message')
            elif can_review and 'review' in request.POST:
                # Запрос на создание рецензии к этому произведению
                request.session['fosterling'] = work
                return HttpResponseRedirect('table?select=new')
            elif is_authorized and not is_recommend and 'recommend' in request.POST:
                # Добавить в список рекомендуемого
                Bookcase.objects.get(user=request.user).recommended.add(work)
                is_recommend = True
            elif is_authorized and not is_favorite and 'favorite' in request.POST:
                # Добавить в список избранного
                Bookcase.objects.get(user=request.user).favorites.add(work)
                is_favorite = True
            elif is_authorized and is_recommend and 'unrecommend' in request.POST:
                # Убрать из списка рекомендуемого
                Bookcase.objects.get(user=request.user).recommended.remove(work)
                is_recommend = False
            elif is_authorized and is_favorite and 'unfavorite' in request.POST:
                # Убрать из списка избранного
                Bookcase.objects.get(user=request.user).favorites.add(work)
                is_favorite = False
            
            if donate > 0 and not is_master:
                if not _donate_work(request, donate, work):
                    _make_has_no_money_message(request.user, request.profile)
                    return HttpResponseRedirect('message')
                else:
                    return HttpResponseRedirect('table?view=%d' % work.id)
        
        if 'comment_post' in request.session:
            comment_post = request.session['comment_post']
            del request.session['comment_post']
            
            if can_comment and not im_banned and 'comment' in comment_post:
                # Запрос на работу с комментарием
                try:
                    target_comment = int(comment_post['comment'])
                    if 'action' in comment_post:
                        action = comment_post['action']
                        if action == 'ban' and is_master:
                            comment = Comment.objects.get(id=target_comment)
                            rels = WorkRels.objects.get(work=work)
                            rels.banned.add(comment.author)
                            work_ban_list[comment.author.username] = comment.author.id
                            target_comment = 0
                        elif action == 'unban' and is_master:
                            comment = Comment.objects.get(id=target_comment)
                            rels = WorkRels.objects.get(work=work)
                            rels.banned.remove(comment.author)
                            del work_ban_list[comment.author.username]
                            target_comment = 0
                        elif action == 'del' and is_master:
                            comment = Comment.objects.get(id=target_comment)
                            comment.delete()
                            target_comment = 0
                except:
                    target_comment = 0
            elif can_comment and not im_banned and 'answer' in comment_post and 'root' in comment_post and 'title' in comment_post:
                # Добавление нового комментария
                comment_answer_title = comment_post['title']
                comment_answer = comment_post['answer']
                if comment_answer:
                    try:
                        comment_root_id = int(comment_post['root'])
                        root = Comment.objects.get(id=comment_root_id)
                        Comment.objects.create_comment(author=request.user, text=comment_answer, root=root,
                                                       title=comment_answer_title or u'Re. %s' % root.title)
                    except:
                        pass
        
        if not is_master and is_authorized and work.price > 0:
            # Выставить предложение о продаже произведения
            table_data['price'] = '%.2f' % work.price
        
        table_data['like'] = like_it
        table_data['dislike'] = dislike_it
        table_data['fosterling'] = work.fosterling
        table_data['pages'] = Page.objects.filter(work=work, edition=work.edition).order_by('index')
        
        # Создать список комментариев к этому произведению
        comments = []
        work_comments = WorkComments.objects.get(work=work, edition=work.edition)
        comments.append({ 'level': 0, 'comment': work_comments.comments })
        
        if is_master:
            master_id = request.user.id
        else:
            master_id = 0
        
        if is_authorized:
            user_id = request.user.id
        else:
            user_id = 0
        
        _append_sub_comments(comments, work_comments.comments, 1, master_id,
                             user_id, ban_list, work_ban_list, ignor_list)
        
        # Создать список рецензий для этого произведения
        reviews = Work.objects.filter(fosterling=work).exclude(status=u'draft').order_by('date')
        if len(reviews) > 0:
            review_list = []
            for review in reviews:
                if not review.author.username in ban_list \
                and not review.author.username in ignor_list \
                and not review.author.username in master_ignor_list:
                    review_list.append(review)
        else:
            review_list = None
        
        visit, unique = _register_visit(work, request.user, is_published and not is_master)
        
        summ = None
        if is_master:
            summ = Transaction.objects.filter(work=work, recipient=work.owner or work.author).aggregate(Sum('cash'))['cash__sum']
        if not summ:
            summ = 0
        
        table_data['contest'] = work.contest
        table_data['is_favorite'] = is_favorite
        table_data['is_recommend'] = is_recommend
        table_data['visit'] = visit
        table_data['unique'] = unique
        table_data['summ'] = '%.2f' % summ
        table_data['im_banned'] = im_banned
        table_data['im_ignored'] = im_ignored
        table_data['comments'] = comments
        table_data['reviews'] = review_list
        table_data['can_review'] = can_review
        table_data['target_comment'] = target_comment
        table_data['can_comment'] = can_comment
    
    table_data['is_published'] = is_published
    return direct_to_template(request, 'work/work_view.html', table_data)



def _register_visit(work, user, do_register=True):
    """ Вспомогательная функция, регистрирует посещение произведения """
    if user.is_authenticated() and do_register:
        visitor = Visitor.objects.get_or_create(user=user, work=work)[0]
        Visit.objects.create_visit(visitor=visitor)
    visit = Visit.objects.filter(visitor__work=work).count()
    unique = Visitor.objects.filter(work=work).count()
    return (visit, unique)



def _append_sub_comments(comments, root, level, master_id=0, user_id=0,
                         ban_list=None, work_ban_list=None, ignor_list=None):
    """ Рекурсивная функция для создания дерева комментариев """
    work_comments = Comment.objects.filter(root=root).order_by('date')
    for comment in work_comments:
        name = Profile.get_user_name(user=comment.author)[0]
        comments.append({ 'level': level, 'comment': comment, 'author': name, 'author_id': comment.author.id,
                          'can_ban': master_id and comment.author.id != master_id,
                          'can_del': user_id and comment.author.id == user_id,
                          'banned': ban_list and comment.author.username in ban_list,
                          'work_banned': work_ban_list and comment.author.username in work_ban_list,
                          'ignored': ignor_list and comment.author.username in ignor_list })
        _append_sub_comments(comments, comment, level + 1, master_id, user_id, ban_list, work_ban_list, ignor_list)



def _make_has_no_money_message(user, profile):
    """ Вспомогательная функция, создает сообщение о нехватке денег у пользователя """
    name, gender = Profile.get_user_name(user=user, profile=profile)
    LrMessage.objects.create_message(user=user, title=u'Не достаточно средств',
                         description=render_to_string('messages/has_no_money.html',
                                                      { 'gender': gender, 'name': name }))



def _pay_for_view(request, work):
    """ Вспомогательная функция оплаты пользователем права просмотра произведения """
    if work.view_price > 0:
        try:
            Transaction.objects.create_transaction(cash=work.view_price, detail=u'Оплата доступа "%s"' % work.title,
                                                   sender=request.user, recipient=work.owner or work.author, work=work)
            _check_generosity(request=request, summ=work.view_price, work=work)
        except BankException:
            return False
    WorkRels.objects.get(work=work).viewers.add(request.user)
    return True



def _donate_work(request, summ, work):
    """ Вспомогательная функция внесения пожертвования на счет произведения """
    try:
        Transaction.objects.create_transaction(cash=summ, detail=u'Добровольный взнос "%s"' % work.title,
                                               sender=request.user, recipient=work.owner or work.author, work=work)
        _check_generosity(request=request, summ=summ, work=work)
    except BankException:
        return False
    return True



def _check_generosity(request, summ, work=None):
    """ Проверить, не надонатил ли юзер на приглашение """
    if not request.profile.is_writer():
        # Проверить, не надонатил ли юзер на приглашение
        donate = Transaction.objects.filter(sender=request.user).exclude(work=None).aggregate(Sum('cash'))['cash__sum']
        old_value = donate - summ
        invites_count = int(donate / settings.DONATE_LIMIT_FOR_GET_INVITE) - int(old_value / settings.DONATE_LIMIT_FOR_GET_INVITE)
        if invites_count > 0:
            while invites_count > 0:
                Invite.objects.create_invite(owner=request.user)
                invites_count -= 1
            LrMessage.objects.create_message(user=request.user, title=u'Новое приглашение',
                                             description=u'Уважаемый меценат! За вашу щедрость Администрация сайта \
                                             дарит вам Приглашение. Вы можете найти его <a href="cabinet?select=invites">в своем Кабинете</a> \
                                             и использовать по своему усмотрению.')
    if work:
        _check_writer_for_new_level(work.author)



def _check_writer_for_new_level(writer):
    """ Проверить, сколько средств собрали произведения автора, и перевести
    его на новый уровень, если он достиг установленного предела """
    profile = Profile.objects.get(user=writer)
    cash = Transaction.objects.filter(work__author=writer).aggregate(Sum('cash'))['cash__sum']
    for rank in settings.WRITER_LEVEL_UP_LIMITS:
        limit = settings.WRITER_LEVEL_UP_LIMITS[rank]
        if cash < limit:
            if profile.rank < rank:
                # Присвоить писателю новый ранг
                profile.rank = rank
                profile.save()
                # Выдать писателю приглашение
                Invite.objects.create_invite(owner=writer)
                LrMessage.objects.create_message(user=writer, title=u'Вам присвоен новый ранг',
                                                 description=u'Уважаемый Писатель, читетели по достоинству оценили ваш труд - \
                                                 кассовый сбор от ваших работ превысил <b>%.2f талантов</b>, в связи с чем вам присвоен \
                                                 <b>%d ранг</b>! Кроме этого вы получаете в свое распоряжение Приглашение, которое \
                                                 вы сможете подарить другу.<br/>Искренне поздравляем вас и желаем дальнейших успехов!' % (limit, rank))
            break



def _vote_work(like, user, work):
    """ Вспомогательная функция голосования за произведение """
    if like:
        WorkRels.objects.get(work=work).likers.add(user)
        work.like += 1
        work.save()
    else:
        WorkRels.objects.get(work=work).dislikers.add(user)
        work.dislike += 1
        work.save()        



def _buy_work(request, work):
    """ Вспомогательная функция, покупка пользователем произведения """
    if work.price > 0:
        try:
            Transaction.objects.create_transaction(cash=work.price, detail=u'Покупка произведения "%s"' % work.title,
                                                   sender=request.user, recipient=work.owner or work.author, work=work)
            _check_generosity(request=request, summ=work.price, work=work)
        except BankException:
            return False
    # Удалить старых соавторов и доверенных лиц
    rels = WorkRels.objects.get(work=work)
    rels.coauthors.clear()
    rels.trustee.clear()
    # Установить нового пользователя
    if request.user == work.author:
        work.owner = None
    else:
        work.owner = request.user
    work.status = u'draft'
    work.save()
    return True